package com.server.http.anYuan;

import com.server.dao.AlarmDao;
import com.server.dao.MobileAppDao;
import com.server.dao.UnitDao;
import com.server.libs.login.data.AppCache;
import com.server.libs.login.AppOline;
import com.server.pojo.MobileApp;
import com.server.pojo.Unit;
import com.server.push.OnlinePush;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@Configuration
@EnableScheduling    //开启定时任务
@Slf4j
@Transactional
public class AnYuanTask {
    @Autowired
    MobileAppDao mobileAppDao;
    @Autowired
    AlarmDao alarmDao;
    @Autowired
    UnitDao unitDao;
    @Autowired
    OnlinePush onlinePush;

    @Autowired
    AppOline appOline;


    //每3秒执行一次
    @Scheduled(fixedDelay = 12*60*60*1000)
    public void updateUnit() {

        List<Unit> all = unitDao.findAll();
        List<Unit> anYuanUnits = AnYuanServer.getUnit();

        for (Unit anYuanUnit : anYuanUnits) {
            boolean isHave = false;
            for (Unit unit : all) {
                if (anYuanUnit.getCode().equals(unit.getCode())){
                    unit.setAddr(anYuanUnit.getAddr());
                    unit.setName(anYuanUnit.getName());
                    unitDao.save(unit);
                    isHave = true;
                    break;
                }
            }
            if (isHave) continue;

            Unit unit = new Unit();
            unit.setCode(anYuanUnit.getCode());
            unit.setAddr(anYuanUnit.getAddr());
            unit.setName(anYuanUnit.getName());
            System.out.println(unit);
            unitDao.save(unit);
        }

    }



    @Scheduled(fixedDelay = 5*60*1000)
    @Transactional
    public void heart() {
        List<AppCache> all = appOline.getAll();
        List<Integer> ids = all.stream().map(var -> var.id).collect(Collectors.toList());
        List<MobileApp> online = mobileAppDao.findByIdIn(ids);
        AnYuanServer.sendOlineApp(new ArrayList<>(online),6000);
    }




}
